package com.xusl.spring.proxy;

import com.xusl.spring.transaction.TransactionManager;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;

/**
 * @Author: xusl
 * @Date: 2021/8/4 10:59 下午
 */
public class Proxy {

    private TransactionManager tcm;

    public void setTcm(TransactionManager tcm) {
        this.tcm = tcm;
    }

    /**
     * 获取代理对象
     *
     * @param obj
     * @return
     */
    public Object getCglibProxy(Object obj) {

        return Enhancer.create(obj.getClass(), (MethodInterceptor) (o, method, objects, methodProxy) -> {
            Object result = null;
            try {
                System.out.println("obj接口执行前置增强");
                tcm.startTransaction();


                result = method.invoke(obj, objects);

                System.out.println("obj接口执行后置增强");
                tcm.commit();
            } catch (Exception e) {
                e.printStackTrace();
                tcm.rollback();
                throw e;
            }

            // 被代理对象执行结果返回
            return result;
        });
    }


    /**
     * @param obj 被代理对象(接口实例)
     * @return
     */
    public Object getJDKProxy(Object obj) {
        // 返回代理对象
        Object proxyInstance = java.lang.reflect.Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), (proxy, method, args) -> {
            Object result = null;
            try {
                System.out.println("obj接口执行前置增强");
                tcm.startTransaction();

                result = method.invoke(obj, args);

                System.out.println("obj接口执行后置增强");
                tcm.commit();
            } catch (Exception e) {
                e.printStackTrace();
                tcm.rollback();
                throw e;
            }

            // 被代理对象执行结果返回
            return result;
        });

        // 返回代理对象实例
        return proxyInstance;
    }
}
